package com.cavytech.wear;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.support.v7.internal.widget.AdapterViewCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

import java.util.ArrayList;

public class TestActivity extends Activity {
    Button mButtonBind, mButtonExit, mButtonVibrate, mButtonLight;
    TextView mTextViewData;
    Spinner mSpinnerDevice;
    ArrayList<String> mDeviceList = null;
    String mDevice;

    final static String TAG = "TestActivity";

    BraceletClient mBraceletClient = null;
    Messenger mBraceletMessenger = new Messenger(new IncomingHandler());

    class IncomingHandler extends Handler {

        public void handleMessage(Message msg) {
            Bracelet.dump(TAG + "(RECV)", msg);
            switch(msg.what) {
                case Bracelet.CMD_ACK:
                    break;

                case Bracelet.CMD_DEVICES:
                    mBraceletClient.sendACK(msg, true);
                    LoadDevice(msg.getData().getStringArrayList(Bracelet.KEY_STRING_ARRAY));
                    break;

                case Bracelet.CMD_DATA:
                    mBraceletClient.sendACK(msg, true);
                    LoadData(msg.getData().getByteArray(Bracelet.KEY_BYTE_ARRAY));
                    break;

                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    }

     @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_test);

         mButtonBind = (Button)findViewById(R.id.ButtonBind);
         mButtonExit = (Button)findViewById(R.id.ButtonExit);
         mButtonVibrate = (Button)findViewById(R.id.ButtonVibrate);
         mButtonLight = (Button)findViewById(R.id.ButtonLight);
         mTextViewData = (TextView)findViewById(R.id.TextViewData);
         mSpinnerDevice = (Spinner)findViewById(R.id.SpinnerDevice);

         mButtonBind.setOnClickListener(buttonBindListener);
         mButtonExit.setOnClickListener(buttonExitListener);
         mButtonVibrate.setOnClickListener(buttonVibrateListener);
         mButtonLight.setOnClickListener(buttonLightListener);
         mSpinnerDevice.setOnItemSelectedListener(new OnItemSelectedListener() {
             @Override
             public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                 mDevice = new String( parent.getSelectedItem().toString() );
                 Log.d(TAG, "Device:" + mDevice);
                 updateStatus();
             }

             @Override
             public void onNothingSelected(AdapterView<?> parent) {

             }
         });

         mDeviceList = new ArrayList<String>();
         mBraceletClient = new BraceletClient(this, TAG, mBraceletMessenger);

         updateStatus();
    }

    protected void onDestroy() {
        mBraceletClient.UnbindService();
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_test, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return super.onOptionsItemSelected(item);
    }

    private void updateStatus() {
        if (mBraceletClient.mIsBind) {
            mButtonBind.setText(R.string.Unbind);
        } else {
            mButtonBind.setText(R.string.Bind);
            mTextViewData.setText("");
            mSpinnerDevice.setAdapter(null);
        }

        boolean enable = mBraceletClient.mIsBind && mDeviceList.size() != 0;

        mButtonVibrate.setEnabled(enable);
        mButtonLight.setEnabled(enable);
        mSpinnerDevice.setEnabled(enable);
    }

    private void LoadData(byte[] data) {
        if(data==null) {
            Log.d(TAG, "Empty Data");
            return;
        }

        String DeviceAddress = "";
        // First 6 bytes is device address.
        for ( int j = 0; j < 6; j++ ) {
            DeviceAddress += Integer.toHexString(data[j]&0xFF|0x100).substring(1).toUpperCase();
            if ( j != 5 )
                DeviceAddress += ":";
        }

        String showString = "";
        if( true ) { // Show focus device data only
            if(!mDevice.contentEquals(DeviceAddress))
                return;
        } else { // Show all devices data
            showString = "Device [ " + DeviceAddress + " ]\n";
        }

        // The meat after the device address are device data.
        for (int j = 6; j < data.length; j++)
            showString += Integer.toHexString(data[j] & 0xFF | 0x100).substring(1).toUpperCase() + " ";

        mTextViewData.setText(showString);
    }

    private void LoadDevice( ArrayList<String> deviceList ) {
        mDeviceList = new ArrayList<String>(deviceList);
        ArrayAdapter<String> listAdapter;
        listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, mDeviceList);
        mSpinnerDevice.setAdapter(listAdapter);
        if(mDeviceList.size() > 0)
            mSpinnerDevice.setSelection(0);
    }

    private OnClickListener buttonBindListener = new OnClickListener() {
        public void onClick(View v) {
            if( mBraceletClient.mIsBind ) {
                mBraceletClient.UnbindService();
            } else {
                mBraceletClient.BindService();
            }
            updateStatus();
        }
    };

    private OnClickListener buttonExitListener = new OnClickListener() {
        public void onClick(View v) {
            TestActivity.this.finish();
        }
    };

    private OnClickListener buttonVibrateListener = new OnClickListener() {
        public void onClick(View v) {
            String cmd = mDevice + "%VIBRATE=1,50,500";
            byte[] data = new byte[cmd.length()];

            try {
                data = cmd.getBytes("UTF-8");
            } catch(Exception e) {
                e.printStackTrace();
            }

            mBraceletClient.sendCommand(Bracelet.CMD_DATA,0,data);
        }
    };

    private OnClickListener buttonLightListener = new OnClickListener() {
        public void onClick(View v) {
            String cmd = mDevice + "%LED=2,2,30,100,2000\n";
            byte[] data = new byte[cmd.length()];

            try {
                data = cmd.getBytes("UTF-8");
            } catch(Exception e) {
                e.printStackTrace();
            }

            mBraceletClient.sendCommand(Bracelet.CMD_DATA,0,data);
        }
    };
}
